﻿using BaseSimpleDao;
using BaseSimpleAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonHelper;
using PetaPoco.NetCore;

namespace BaseSimpleAPI
{
    public class BaseEditModel { public virtual long Id { get; set; } }

    public class BaseViewModel { public virtual long Id { get; set; } }

    /// <summary>
    /// 基础接口
    /// </summary>
    public class BaseController
    {
        /// <summary>
        /// 请求对象
        /// </summary>
        public INetRequest Request { get { return TagHelper.Current.GetData<INetRequest>(); } }

        /// <summary>
        /// 返回一个Json数据对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected IActionResult Json(object obj)
        {
            return new ObjectResult(obj);
        }

        protected IActionResult Error(string message)
        {
            return Json(StatusData.Error(message));
        }

        /// <summary>
        /// 返回一个没有权限的结果
        /// </summary>
        /// <returns></returns>
        protected IActionResult NoPermissions()
        {
            return Error(StatusDataPrompt.GetStatusDataPrompt().NoPermissions);
        }

        /// <summary>
        /// 模型数据检查失败
        /// </summary>
        /// <returns></returns>
        protected IActionResult ModelCheckFailed()
        {
            return Error(StatusDataPrompt.GetStatusDataPrompt().ModelCheckFail);
        }

        /// <summary>
        /// 状态数据结果
        /// </summary>
        /// <param name="status"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        protected IActionResult JsonStatusData(StatusDataStatus status, string message = null)
        {
            return Json(new StatusData { Status = status, Message = message });
        }

        /// <summary>
        /// 状态数据结果
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="msg"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        protected IActionResult JsonStatusData(object obj, string msg = null, StatusDataStatus status = StatusDataStatus.Success)
        {
            return Json(new StatusObjectData { Data = obj, Message = msg, Status = status });
        }
    }

    /// <summary>
    /// 泛型接口
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <typeparam name="TEditModel"></typeparam>
    /// <typeparam name="TViewModel"></typeparam>
    public class BaseController<TModel, TEditModel, TViewModel> : BaseController
        where TModel : BaseModel
        where TEditModel : BaseEditModel
        where TViewModel : BaseViewModel
    {
        private BaseService<TModel> _Service = new BaseService<TModel>();

        public virtual BaseService<TModel> Service { get { return _Service; } }

        public virtual AuthorizationStatus GetAuthorizationStatus(string action, long requestid, long objectid = 0) { return AuthorizationStatus.Accept; }

        protected TPage<T2> ChangePage<T1, T2>(Page<T1> page)
        {
            TPage<T2> temp = new TPage<T2>();

            temp.CurrentPage = page.CurrentPage;
            temp.ItemsPerPage = page.ItemsPerPage;
            temp.TotalItems = page.TotalItems;
            temp.TotalPages = page.TotalPages;

            temp.Items = page.Items.Select(n => TypeHelper.Transformation<T2>(n)).ToList();

            return temp;
        }

        /// <summary>
        /// 添加对象
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns> 
        public virtual IActionResult Add(TEditModel model)
        {
            if (GetAuthorizationStatus("Add", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            if (!ModelCheckHelper.CheckModel(model, out string error))
                return ModelCheckFailed();

            TModel db_model = TypeHelper.Transformation<TModel>(model);

            if (!Service.Add(db_model))
                return Error(StatusDataPrompt.GetStatusDataPrompt().Error);

            return JsonStatusData(TypeHelper.Transformation<TViewModel>(db_model));
        }

        /// <summary>
        /// 根据数据对象
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public virtual IActionResult Update(TEditModel model)
        {
            if (GetAuthorizationStatus("Update", Request.GetCurrentUserId(), model.Id) != AuthorizationStatus.Accept)
                return NoPermissions();

            if (!ModelCheckHelper.CheckModel(model, out string error))
                return ModelCheckFailed();

            TModel db_model = TypeHelper.Transformation<TModel>(model);

            if (Service.Update(db_model) <= 0)
                return Error(StatusDataPrompt.GetStatusDataPrompt().Error);

            return JsonStatusData(TypeHelper.Transformation<TViewModel>(db_model));
        }

        /// <summary>
        /// 根据Id删除对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual IActionResult RemoveById(long id)
        {
            if (GetAuthorizationStatus("Update", Request.GetCurrentUserId(), id) != AuthorizationStatus.Accept)
                return NoPermissions();

            return JsonStatusData(Service.RemoveById(id) > 0 ? StatusDataStatus.Success : StatusDataStatus.Error);
        }

        /// <summary>
        /// 根据简单筛选器获取对象
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="value">列值</param>
        /// <returns></returns>
        public virtual IActionResult GetItemBySingleFilter(string name, object value)
        {
            if (GetAuthorizationStatus("GetItemBySingleFilter", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var model = Service.GetItemBySingleFilter(name, value);
            if (model == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(TypeHelper.Transformation<TViewModel>(model));
        }

        /// <summary>
        /// 获取全部对象
        /// </summary>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetAll(List<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetAll", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var models = Service.GetAll(orders);
            if (models == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(models.Select(n => TypeHelper.Transformation<TViewModel>(n)).ToList());
        }

        /// <summary>
        /// 获取前N条数据
        /// </summary>
        /// <param name="count">数据限制</param>
        /// <param name="filters">筛选器</param>
        /// <param name="orders">排序依据</param>
        /// <returns></returns>
        public virtual IActionResult GetTop(int count, List<BaseFilter> filters = null, List<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetTop", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var models = Service.GetTop(count, filters, orders);
            if (models == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(models.Select(n => TypeHelper.Transformation<TViewModel>(n)).ToList());
        }

        /// <summary>
        /// 根据Id获取列表对象
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetListByIds(List<long> ids, List<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetListByIds", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var models = Service.GetListByIds(ids, orders);
            if (models == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(models.Select(n => TypeHelper.Transformation<TViewModel>(n)).ToList());
        }

        /// <summary>
        /// 根据筛选对象获取列表
        /// </summary>
        /// <param name="filters"></param>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetListByFilter(IEnumerable<BaseFilter> filters, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetListByFilter", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var models = Service.GetListByFilter(filters, orders);
            if (models == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(models.Select(n => TypeHelper.Transformation<TViewModel>(n)).ToList());
        }

        /// <summary>
        /// 根据简单筛选器获取列表数据
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="value">列值</param>
        /// <param name="orders">排序依据</param>
        /// <returns></returns>
        public virtual IActionResult GetListBySingleFilter(string name, object value, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetListBySingleFilter", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var models = Service.GetListBySingleFilter(name, value, orders);
            if (models == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(models.Select(n => TypeHelper.Transformation<TViewModel>(n)).ToList());
        }

        /// <summary>
        /// 获取第一个或者默认的对象
        /// </summary>
        /// <param name="filters">筛选器</param>
        /// <param name="orders">排序依据</param>
        /// <returns></returns>
        public virtual IActionResult GetFirstOrDefault(IEnumerable<BaseFilter> filters, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetFirstOrDefault", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var model = Service.GetFirstOrDefault(filters, orders);
            if (model == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(TypeHelper.Transformation<TViewModel>(model));
        }

        /// <summary>
        /// 根据Id获取具体数据对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual IActionResult GetItemById(long id)
        {
            if (GetAuthorizationStatus("GetItemById", Request.GetCurrentUserId(), id) != AuthorizationStatus.Accept)
                return NoPermissions();

            var model = Service.GetItemById(id);
            if (model == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(TypeHelper.Transformation<TViewModel>(model));
        }

        /// <summary>
        /// 根据筛选器获取数据数量
        /// </summary>
        /// <param name="filters">筛选器</param>
        /// <returns></returns>
        public virtual IActionResult GetCount(IEnumerable<BaseFilter> filters = null)
        {
            if (GetAuthorizationStatus("GetCount", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var count = Service.GetCount(filters);
            return JsonStatusData(count);
        }

        /// <summary>
        /// 根据筛选器获取数据Id列表
        /// </summary>
        /// <param name="filters">筛选器</param>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetItemIdList(IEnumerable<BaseFilter> filters = null, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetItemIdList", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var ids = Service.GetItemIdList(filters, orders);
            if (ids == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(ids);
        }

        /// <summary>
        /// 获取前N条数据的Id
        /// </summary>
        /// <param name="count">数量限制</param>
        /// <param name="filters">过滤器</param>
        /// <param name="orders">排序依据</param>
        /// <returns></returns>
        public virtual IActionResult GetTopIdList(int count, IEnumerable<BaseFilter> filters = null, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetTopIdList", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var ids = Service.GetItemIdList(filters, orders);
            if (ids == null)
                return Error(StatusDataPrompt.GetStatusDataPrompt().NotFindObjects);

            return JsonStatusData(ids);
        }

        /// <summary>
        /// 获取第一个或者默认的数据对象Id
        /// </summary>
        /// <param name="filters"></param>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetFirstOrDefaultId(IEnumerable<BaseFilter> filters = null, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetFirstOrDefaultId", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var id = Service.GetFirstOrDefaultId(filters, orders);
            return JsonStatusData(id);
        }

        /// <summary>
        /// 获取分页数据列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="itemsPerPage">每页数量</param>
        /// <param name="filters">过滤器</param>
        /// <param name="orders">排序依据</param>
        /// <returns></returns>
        public virtual IActionResult GetPage(int page, int itemsPerPage, IEnumerable<BaseFilter> filters, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetPage", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var page_model = Service.GetPage(page, itemsPerPage, filters, orders);
            return JsonStatusData(ChangePage<TModel, TViewModel>(page_model));
        }

        /// <summary>
        /// 根据id获取所在分页数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="filters"></param>
        /// <param name="orders"></param>
        /// <returns></returns>
        public virtual IActionResult GetPageIndex(long id, int itemsPerPage, IEnumerable<BaseFilter> filters, IEnumerable<BaseOrder> orders = null)
        {
            if (GetAuthorizationStatus("GetPageIndex", Request.GetCurrentUserId()) != AuthorizationStatus.Accept)
                return NoPermissions();

            var value = Service.GetPageIndex(id, itemsPerPage, filters, orders);
            return JsonStatusData(value);
        }
    }
}
